import React, { PureComponent } from 'react'
import { Button, Form, Select, Row, Icon, Upload, Input, message } from 'antd'
import { debounce } from 'utils'
import PropTypes from 'prop-types'

import Style from './scenesCom.css'

const { TextArea } = Input
const { Option } = Select
const formItemLayout = {
  labelCol: { span: 9 },
  wrapperCol: { span: 8 }
}

const formTailLayout = {
  labelCol: { span: 9 },
  wrapperCol: { span: 8, offset: 9 }
}

class ScenesComForm extends PureComponent {
  constructor (props) {
    super(props)
    this.state = {
    }
    this.onChange = this.onChange.bind(this)
    this.handlePrevious = this.handlePrevious.bind(this)
    this.categoryChange = this.categoryChange.bind(this)
    this.nameChange = this.nameChange.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.desChange = this.desChange.bind(this)
  }

  beforeUpload (file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传JPG/PNG格式的图片!')
      this.setState({
        loading: false
      })
      return false
    }
    const isLt2M = file.size / 1024 / 1024 < 64
    if (!isLt2M) {
      message.error('图片大小 64MB!')
      this.setState({
        loading: false
      })
      return false
    }
    return isJpgOrPng && isLt2M
  }

  onChange ({ file, fileList, event }) {
    if (file.status !== 'uploading') {
      this.setState({
        loading: true
      })
    }

    if (file.status === 'error') {
      message.error('上传失败')
      this.setState({
        loading: false
      })
      return
    }

    if (file.status === 'done') {
      this.props.imageChange(file.response && file.response.data.imageUrl)
      this.setState({
        loading: false,
        image: file.response && file.response.data.imageUrl
      })
    }

    if (!file.status) {
      this.setState({
        loading: false
      })
    }
  }

  categoryChange (e) {
    this.setState({
      categoryCode: e
    })
    this.props.categoryChange(e)
  }

  nameChange (e) {
    this.props.nameChange(e.target.value)
  }

  desChange (e) {
    this.props.desChange(e.target.value)
  }

  handlePrevious (e) {
    e.preventDefault()
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.stepChange()
      }
    })
  }

  // componentWillReceiveProps (nextProps) {
  //   if (!this.props.image && nextProps.image) {

  //     this.setState({
  //       image: nextProps.image
  //     })
  //   }
  // }

  render () {
    const { name, categoryCode, image: imageCp, description } = this.props
    const { getFieldDecorator } = this.props.form
    const { loading, image } = this.state
    const uploadButton = (
      <div className={Style[`${image ? '' : 'image-container'}`]}>
        {
          (image || imageCp) ? <div className={Style['image']} style={{ backgroundImage: `url(${image || imageCp})` }} /> : <>
            <Icon type={loading ? 'loading' : 'plus'} />
            <div className={Style['ant-upload-text']}>Upload</div></>
        }
      </div>
    )
    return (
      <div className={Style['scenes-com']}>
        <Row>
          <Form {...formItemLayout} autoComplete='off'>
            <Form.Item label='场景名称'>
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入场景名称' }],
                initialValue: name
              })(
                <Input placeholder='请输入场景名称' onChange={(e) => debounce(this.nameChange(e), 300)} />
              )}
            </Form.Item>
            <Form.Item label='场景描述'>
              {getFieldDecorator('description', {
                rules: [{ required: true, message: '请输入场景描述' }],
                initialValue: description
              })(
                <TextArea placeholder='请输入场景描述' onChange={(e) => debounce(this.desChange(e), 300)} />
              )}
            </Form.Item>
            <Form.Item label='场景类别'>
              {getFieldDecorator('categoryCode', {
                rules: [{ required: true, message: '请选择场景类别' }],
                initialValue: categoryCode
              })(
                <Select placeholder='请选择场景类别' onChange={this.categoryChange}>
                  <Option value='HUMAN_SPACE'>人文空间</Option>
                  <Option value='FAMILY_SPACE'>家居室内</Option>
                  <Option value='BIZ_SPACE'>商业空间</Option>
                  <Option value='COMMON_SPACE'>公共空间</Option>
                  <Option value='PAVILION_SPACE'>展馆空间</Option>
                  <Option value='OTHER_SPACE'>其他空间</Option>
                </Select>
              )}
            </Form.Item>
            <Form.Item label='上传场景图片' extra={<span style={{ fontSize: '14px', color: 'rgba(0, 0, 0, 0.35)' }}>png格式，图片大小限定1～3M</span>}>
              {getFieldDecorator('image', {
                valuePropName: 'picture',
                initialValue: image || imageCp,
                rules: [{ required: true, message: '请选上传场景图片' }]
              })(
                <Upload
                  action='/file/upload/1.0'
                  name='file'
                  beforeUpload={this.beforeUpload}
                  onChange={this.onChange}
                  showUploadList={false}
                  withCredentials
                  headers={{
                    token: localStorage.getItem('token') || ''
                  }}
                >
                  {uploadButton}
                  <Button>
                    <Icon type='upload' /> 选择上传图片
                  </Button>
                </Upload>
              )}

            </Form.Item>
            <Form.Item {...formTailLayout}>
              <Button type='primary' onClick={this.handlePrevious}>
                选择商品关联
              </Button>
            </Form.Item>
          </Form>
        </Row>
      </div>
    )
  }
}

const ScenesCom = Form.create()(ScenesComForm)

ScenesCom.propTypes = {
  stepChange: PropTypes.func
}
export default ScenesCom
